/*This source code copyrighted by Lazy Foo' Productions (2004-2012)
 and may not be redistributed without written permission.*/

//The headers
#include "SDL/SDL.h"
#include <string>
#include "Timer.h"
#include "Player.h"
#include "SurfaceOps.h"
#include "Screen.h"
#include "Flame.h"
#include <vector>
#include <iostream>

using namespace std;

//The frames per second
const int FRAMES_PER_SECOND = 20;

//The event structure
SDL_Event event;

bool init()
{
	//Initialize all SDL subsystems
	if (SDL_Init(SDL_INIT_EVERYTHING) == -1)
	{
		return false;
	}

	//Set the window caption
	SDL_WM_SetCaption("Simple Directdraw Library Test", NULL);

	//If everything initialized fine
	return true;
}

int main(int argc, char* args[])
{
	//Quit flag
	bool quit = false;

	//The event structure
	SDL_Event event;

	//Initialize
	if (init() == false)
	{
		return 1;
	}

	Screen screen;

	//The frame rate regulator
	Timer fps;

	vector<Flame *> flames;

	//The figure
	Player megaman(&screen, &flames);

	//While the user hasn't quit
	while (quit == false)
	{
		//Start the frame timer
		fps.start();

		//While there's events to handle
		while (SDL_PollEvent(&event))
		{
			//Handle events for the stick figure
			megaman.handleEvents(&event);

			//If the user has Xed out the window
			if (event.type == SDL_QUIT)
			{
				//Quit the program
				quit = true;
			}
		}

		//Move the stick figure
		megaman.move();
		for(int i=0; i<flames.size(); )
		{
			if(flames[i]->finished())
			{
				delete flames[i];
				flames.erase(flames.begin()+i);
			}
			else
			{
				flames[i]->move();
				i++;
			}
		}

		SDL_Rect camera = megaman.setCamera();

		//Repaint the screen
		screen.repaint(camera);

		//Show the stick figure on the screen
		megaman.show();
		for(int i=0; i<flames.size(); i++)
		{
			flames[i]->show();
		}

		//Update the screen
		if (SDL_Flip(screen.surface()) == -1)
		{
			return 1;
		}

		//Cap the frame rate
		if (fps.getTicks() < 1000 / FRAMES_PER_SECOND)
		{

			//The frame rate as a string std::stringstream caption; //Calculate the frames per second and create the string caption << "Average Frames Per Second: " << frame / ( fps.get_ticks() / 1000.f ); //Reset the caption SDL_WM_SetCaption( caption.str().c_str(), NULL ); //Restart the update timer update.start();
			SDL_Delay((1000 / FRAMES_PER_SECOND) - fps.getTicks());
		}
	}

	SDL_Quit();

	return 0;
}
